{% extends 'IcsocUIBundle::page.html.twig' %}
{% from 'IcsocUIBundle:Macro:grid.html.twig' import gridWidth,gridNav,gridConfig,gridKeyword,sendKeyWord %}
{% block stylesheet %}
    {{ parent() }}
    {% stylesheets
    '@jquery_ui_css'
    '@jqgird_css'
    '@gritter_css'
    '@chosen_css'
    filter='cssrewrite' filter='uglifycss'
    %}
    <link rel="stylesheet" href="{{ asset_url }}" />
    {% endstylesheets %}
{% endblock %}

{% block content %}
    <div class="widget-container-col">
        <div class="widget-box" style="margin: 3px 0px 10px 0" id="tableWidth">
            <!-- /section:custom/widget-box.options -->
            <div class="widget-body">
                <div class="widget-main">
                    <form class="form-inline" id="searchForm">
                        <div class="form-group col-md-3 col-xs-10 col-sm-10">
                            <label for="keyword">{{ 'Keyword'|trans }}: </label>
                            <input type="text" class="form-control input-sm" id="keyword"
                                data-rel="tooltip" title="{{ 'Supports employee number, name of seats, a plurality of search single seat log extension number search, fuzzy search or to English commas (such as: 8001,8002)'|trans }}" data-placement="bottom" data-original-title="{{ 'Keyword'|trans }}">
                        </div>
                        <div class="col-md-5 col-xs-10 col-sm-10">
                            <select data-placeholder="所属角色" id="user_roles" class="chosen-select tag-input-style" style="width:100%;" multiple>
                                {% for key,role in roleValues %}
                                    <option value="{{ key }}" >{{ role }}</option>
                                {% endfor %}
                            </select>
                        </div>
                        <button id="loading-btn" type="button" class="btn btn-sm btn-info" data-loading-text="Loading...">
                            <i class="ace-icon fa fa-search"></i>{{ 'Inquiry'|trans }}
                        </button>
                    </form>
                </div>
            </div>
        </div>
    </div>
    <table id="grid-table"></table>
    <div id="grid-pager"></div>
    <div>
        <button onclick="selectAll(1, true)" class="btn btn-primary btn-round align-middle btn-sm">{{ 'Select all'|trans }}</button>
        <button onclick="selectAll(2)" class="btn btn-primary btn-round align-middle btn-sm">{{ 'Select not all'|trans }}</button>
        {% if isAdmin %}
            <button onclick="resetAllReadyAgent()" class="btn btn-primary btn-round align-middle btn-sm">刷新全部静态坐席</button>
        {% endif %}
        <button onclick="exportAgent()" class="btn btn-primary btn-round align-middle btn-sm">{{ 'Export Excel'|trans }}</button>
        <span>{{ 'You have chosen'|trans }}<b id="selectNum">0</b>{{ 'Line'|trans }}</span>
    </div>
    <div id="batch" class="hide">
        <div class="widget-box">
            <div class="widget-header">
                <h4 class="widget-title">{{ 'Batch modify'|trans }}</h4>
                <div class="widget-toolbar">
                    <a href="#" data-action="collapse">
                        <i class="ace-icon fa fa-chevron-up"></i>
                    </a>
                </div>
            </div>
            <div class="widget-body">
                <div class="widget-main">
                    <form class="form-horizontal" id="theForm" method="post" action="{{ path('icsoc_agent_batch_insert') }}">
                        <div class="form-group">
                            <label for="agent_info_form_user_role" class="col-sm-1 control-label no-padding-right required" >{{ 'Username'|trans }}</label>
                            <div class="col-md-2">
                                <input type="text" id="username" placeholder="{{ 'Username'|trans }}" class="col-xs-10 col-sm-10">
                            </div>
                            <label for="agent_info_form_user_role" class="col-sm-1 control-label no-padding-right " >{{ 'Nickname'|trans }}</label>
                            <div class="col-md-2">
                                <input type="text" id="nickname" placeholder="{{ 'Nickname'|trans }}" class="col-xs-10 col-sm-10">
                            </div>
                            <label for="agent_info_form_user_role" class="col-sm-1 control-label no-padding-right required" >
                                {{ 'Belongs to the skill set'|trans }}</label>
                            <div class="col-md-2">
                                <select id="belong_ques" name="belong_ques" class="col-xs-10 col-sm-10">
                                    <option value="" selected="selected">{{ 'Default'|trans }}</option>
                                    {% for key,que in queValues %}
                                        <option value="{{ key }}" >{{ que }}</option>
                                    {% endfor %}
                                </select>
                            </div>
                            <label for="agent_info_form_user_role" class="col-sm-1 control-label no-padding-right required" >
                                {{ 'User role'|trans }}</label>
                            <div class="col-md-2">
                                <select id="user_role" name="user_role" class="col-xs-10 col-sm-10">
                                    <option value="" selected="selected">{{ 'Default'|trans }}</option>
                                    {% for key,role in roleValues %}
                                        <option value="{{ key }}" >{{ role }}</option>
                                    {% endfor %}
                                </select>
                            </div>
                        </div>
                        <div class="form-group">
                            {#<label for="agent_info_form_user_role" class="col-sm-1 control-label no-padding-right required" >{{ 'Data access'|trans }}</label>
                            <div class="col-md-2">
                                <select id="user_type" name="user_type" class="col-xs-10 col-sm-10">
                                    <option value="" selected="selected">{{ 'Default'|trans }}</option>
                                    {% for key,data in dataRole %}
                                        <option value="{{ key }}" >{{ data }}</option>
                                    {% endfor %}
                                </select>
                            </div>#}
                            <label for="agent_info_form_user_role" class="col-sm-1 control-label no-padding-right required" >
                                {{ 'The front seat type'|trans }}</label>
                            <div class="col-md-2">
                                <select id="ag_type" name="ag_type" class="col-xs-10 col-sm-10">
                                    <option value="" selected="selected">{{ 'Default'|trans }}</option>
                                    {% for key,type in agType %}
                                        <option value="{{ key }}" >{{ type }}</option>
                                    {% endfor %}
                                </select>
                            </div>
                            {% if isEnableGroup %}
                            <label for="agent_info_form_user_role" class="col-sm-1 control-label no-padding-right required" >
                                {{ 'The business group'|trans }}</label>
                            <div class="col-md-2">
                                <select id="user_group" name="user_group" class="col-xs-10 col-sm-10">
                                    <option value="" selected="selected">{{ 'Default'|trans }}</option>
                                    {% for key,group in groups %}
                                        <option value="{{ key }}" >{{ group }}</option>
                                    {% endfor %}
                                </select>
                            </div>
                            {% endif %}
                            <label for="agent_info_form_user_role" class="col-sm-1 control-label no-padding-right required" >坐席状态</label>
                            <div class="col-md-2">
                                <select id="ag_status" name="ag_status" class="col-xs-10 col-sm-10">
                                    <option value="" selected="selected">{{ 'Default'|trans }}</option>
                                    <option value="1">在职</option>
                                    <option value="2">离职</option>
                                </select>
                            </div>
                        </div>
                        <div class="form-group">
                            <div class="col-sm-9 col-md-offset-3">
                                <button class="btn btn-info" type="button" onclick="batchUpdate()">
                                    <i class="ace-icon fa fa-check bigger-110"></i>
                                    {{ 'Batch modify'|trans }}
                                </button>
                                &nbsp; &nbsp; &nbsp;
                                <button class="btn" type="reset">
                                    <i class="ace-icon fa fa-undo bigger-110"></i>
                                    {{ 'Reset'|trans }}
                                </button>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
    <div id="dialog-confirm" class="hide row">
        {#<label class="col-xs-10 col-sm-3" style="line-height: 34px;width:70px">{{ 'The extension number'|trans }}</label>
        <select name="lpchosen" class="col-xs-10 col-sm-6 chosen-select" id="loginPhone">
            {% for phone in phones %}
                <option value="{{ phone.pho_num }}">{{ phone.pho_num }}</option>
            {% endfor %}
        </select>
        <input type="hidden" id="loginAgNum" value="" />
        <button id="loading-btns" type="button" onclick="set_login()" class="col-xs-10 col-sm-2 btn btn-success btn-sm" data-loading-text="Loading...">
            {{ 'Login'|trans }}
        </button>#}

        <div class="tabbable">
            <ul id="myTab4" class="nav nav-tabs">
                <li id="check" class="active">
                    <a href="#home4" data-toggle="tab">选择添加</a>
                </li>

                <li id="nocheck">
                    <a href="#profile4" data-toggle="tab">手动输入</a>
                </li>
            </ul>

            <div class="tab-content" style="border:0">
                <div class="tab-pane in active" id="home4">
                    <label class="col-xs-10 col-sm-12" style="line-height: 34px;width:70px">{{ 'The extension number'|trans }}</label>
                    <select name="lpchosen" class="col-xs-10 col-sm-6 chosen-select" id="loginPhone">
                        {% for phone in phones %}
                            <option value="{{ phone.pho_num }}">{{ phone.pho_num }}</option>
                        {% endfor %}
                    </select>
                    <input type="hidden" class="loginAgNum loginAgNum1" value="" />
                    <button id="but1" type="button" onclick="" class="col-xs-10 col-sm-2 btn btn-success btn-sm" data-loading-text="Loading...">

                    </button>
                </div>

                <div class="tab-pane" id="profile4">
                    <label class="col-xs-10 col-sm-12" style="line-height: 34px;width:70px">{{ 'The extension number'|trans }}</label>
                    <input type="text" name="lpchosen" id="loginPhone2" class="col-xs-10 col-sm-6" />
                    <input type="hidden" class="loginAgNum loginAgNum2" value="" />
                    <button id="but2" type="button" onclick="" class="col-xs-10 col-sm-2 btn btn-success btn-sm" style="margin-left: 20px" data-loading-text="Loading...">

                    </button>
                </div>
            </div>
        </div>

    </div>

    <div id="dialog-resetAllReady" class="hide row">
        <h5 style="color:red"><span class="ui-icon ui-icon-alert" style="float:left; margin:12px 12px 20px 0;"></span>
            确认更新所有静态坐席？
        </h5>
    </div>
{% endblock %}
{% block footer %}
    {% javascripts
    '@jqgird_js'
    '@jquery_ui_js'
    '@gritter_js'
    '@common_js'
    '@chosen_js'
    filter='uglifyjs'
    %}
    <script src="{{ asset_url }}"></script>
    {% endjavascripts %}
    <script type="text/javascript">
    var isSelectAll = 3;
    var isCancelSelect = [];
    var isSelectedIds = []; //用于非全选用；
    var countRecord = 0;
    var filter = new Object();
    Array.prototype.remove=function(dx){
        if (isNaN(dx) || dx > this.length) {
            return false;
        }
        for (var i= 0,n=0;i<this.length;i++) {
            if (this[i] != this[dx]) {
                this[n++] = this[i]
            }
        }
        this.length-=1;
    };
    jQuery(function($) {
        $('#user_roles').chosen({max_selected_options:3,width:'100%'});
        {{ gridWidth() }}
        {% if filter is not empty %}
            {% if filter.keyword %}
                $('#keyword').val('{{ filter.keyword }}');
                filter.keyword = '{{ filter.keyword }}';
            {% endif %}
            {% if filter.user_role %}
                var userRole = '{{ filter.user_role }}';
                chose_mult_set_ini('#user_roles', userRole);
                filter.user_role = userRole;
            {% endif %}
        {% endif %}
        jQuery(grid_selector).jqGrid({
            url: "{{ path('icsoc_agent_list') }}",  //数据；
            postData: {'isLogin' : {% if allowAction.isLogin %} 1 {% else %} 0 {% endif %},'loginEnter' : {% if allowAction.loginEnter %} 1 {% else %} 0 {% endif %},'loginEdit' : {% if allowAction.loginEdit %} 1 {% else %} 0 {% endif %},'filter':jsonToString(filter)},
            colNames:['','{{ 'actions' | trans}}','ID', '{{ 'Agent number' | trans }}', '{{ 'Username'|trans }}','{{ 'Nickname'|trans }}','{{ 'User role'|trans }}',
                '{{ 'Belongs to the skill set'|trans }}',
                {% if isEnableGroup %}
                '{{ 'The business group'|trans }}',
                {% endif %}
                '{{ 'Data access'|trans}}','{{ 'Seat type'|trans}}','{{ 'CRM permissions'|trans}}','坐席状态' {% if allowAction.isLogin or allowAction.loginEnter or allowAction.loginEdit %},'{{ 'Login status'|trans}}'{% endif %},''],
            colModel:[
                {name:'myac',index:'', width:70, fixed:true, sortable:false, resize:false,
                    formatter: 'actions',
                    formatoptions:{
                        keys:true,
                        editbutton: {% if allowAction.isEdit %}true{% else %}false{% endif %},
                        delbutton: {% if allowAction.isDel %}true{% else %}false{% endif %},
                        editformbutton: {% if allowAction.isEdit %}true{% else %}false{% endif %},
                        delOptions:{recreateForm: true, beforeShowForm:beforeDeleteCallback, afterSubmit:afterDeleteCallback,left:540,top:206},
                        editOptions:{width: "0",height: "0", jqModal: false, display:'none', beforeShowForm:beforeEditCallback },
                    },
                },
                {name:'actions' , index:'actions' , label: '{{ 'actions'|trans }}' , width:40 , sortable:false , fixed:true,formatter:function(value,cell,row){
                    return "<a title='强制退出' href='javascript:void(0);' onclick='agent_operate("+row.ag_id+",4)'><i class='fa fa-sign-out'></i></a>";
                }},
                {name:'id',index:'id',hidden:true, sortable:false, key:true, editable:true},
                {name:'ag_num',width:80,index:'ag_num', sortable:true},
                {name:'ag_name',width:80,index:'ag_name',sortable:true},
                {name:'ag_nickname',width:100,index:'ag_name',sortable:true},
                {name:'role_name',width:80,index:'role_name', sortable:true },
                {name:'queues',width:90,index:'queues', sortable:false,editable:true,formatter:function(cellvalue, options, rowObject){
                    return "<div title='"+rowObject.allqueues+"'>"+cellvalue+"</div>";
                }},
                {% if isEnableGroup %} {name:'group_name',width:90,index:'group_name',sortable:true,editable:true},{% endif %}
                {name:'user_type',width:80,index:'user_type',editable:true, sortable:false },
                {name:'ag_role',width:80,index:'ag_role', editable:true, sortable:false},
                {name:'crm_datarole',width:80,index:'crm_datarole', editable:false, sortable:false },
                {name:'ag_status',width:70,index:'ag_status', editable:false, sortable:false },
                {% if allowAction.isLogin or allowAction.loginEnter or allowAction.loginEdit %}
                    {name:'ag_type',width:180,index:'ag_type', editable:true, sortable:false},
                {% endif %}
                 {name:'is_login',width:100,index:'is_login',hidden:true, editable:true, sortable:false}
            ],
            mtype: 'POST',
            datatype: "json", //从服务器端返回的数据类型，默认xml：xml，local，json，jsonnp，script，xmlstring，jsonstring，clientside
            viewrecords : true, //定义是否要显示总记录数
            rowNum: {{ rows is empty ? 10 : rows }},  //默认每页显示多少条数据
            page: {{ page is empty ? 1 : page }}, //默认第几页
            rowList: [10,20,30,50,100], //每页显示几条数据下拉框的选项
            pager : pager_selector, //翻页工具对象
            height: 'auto',
            sortorder: 'desc',
            altRows: true,  //表格间隔底色
            rownumbers:true,
            multiselect: true,  //是否可以多选
            editurl: "{{ path('icsoc_agent_del') }}",
            caption: "{{ 'Seating list'|trans }}", //表格名称
            loadComplete: function(xhr) {
                countRecord = xhr.records; //总记录数；
                var table = this;
                setTimeout(function(){
                    updatePagerIcons(table);
                }, 0);
                selectAll(isSelectAll);
            },
            onSelectRow:function (rowId, status) {
                //当取消选中 记录到变量中；
                processData(rowId, status);
                if (isSelectAll == 1) {
                    $("#selectNum").text(countRecord - isCancelSelect.length);
                } else {
                   $("#selectNum").text(isSelectedIds.length);
                }
            },
            onSelectAll:function (aRowids, status) {
                for (var i=0; i < aRowids.length; i++) {
                    var rowId = aRowids[i];
                    processData(rowId, status);
                }
                if (isSelectAll == 1) {
                    $("#selectNum").text(countRecord - isCancelSelect.length);
                } else {
                    $("#selectNum").text(isSelectedIds.length);
                }
            }
        });
        {{ gridNav(false,false,allowAction.isDel?true:false,false,true,true,allowAction.isAdd ? path('icsoc_agent_add') : false) }}
        {% if allowAction.isEdit %}
            jQuery(grid_selector).jqGrid('navGrid',pager_selector).navButtonAdd(pager_selector,{caption:'',title:'{{ 'Batch modify'|trans }}',buttonicon:'ace-icon fa fa-edit',onClickButton:function(){
                var ids = $('#grid-table').jqGrid('getGridParam', 'selarrrow');
                if (ids.length < 1) {
                    gritterAlert('{{ 'Prompt'|trans }}','{{ 'Please select a need to modify the data'|trans }}', 'error');
                    return ;
                }
                $('#batch').attr('class', '');
            }});
        {% endif %}
        {% if allowAction.isEdit %}
            jQuery(grid_selector).jqGrid('navGrid',pager_selector).navButtonAdd(pager_selector,{caption:'',title:'{{ 'Batch add'|trans }}',buttonicon:'ace-icon fa fa-code-fork',onClickButton:function(){
                window.location.href='{{ path('icsoc_agent_batch') }}';
            }});
        {% endif %}
        function beforeEditCallback(e){
            var form = $(e[0]);
            var id = form[0].id.value;
            var p = $(grid_selector).getGridParam('page');
            var r = $(grid_selector).getGridParam('rowNum');
            //console.log(form[0].id.value);
            window.location.href = "{{ path('icsoc_agent_edit') }}?id="+id+"&page="+p+"&rows="+r+"&filter="+jsonToString(filter);
        }
        $('#loading-btn').on(ace.click_event, btnSerach);
        $('#searchForm').on('submit', btnSerach);
    });

    function btnSerach(){
        //可以开始获取值进行查询
        var keyword = $('#keyword').val();
        filter.keyword = keyword;
        var $userRole = $('#user_roles').val() || [];
        filter.user_role = $userRole.join(',');
        if ($userRole.length == 0) {
            filter.user_role = 'all';
        }
        var str = jsonToString(filter);
        var arr = {'filter':str};
        $('#grid-table').setGridParam({postData:arr}).trigger("reloadGrid");
        return false;
    }
    /**
     * 批量修改；
     */
    function batchUpdate()
    {
        //获取选中行的ids;
        var username = $('#username').val();
        var belong_ques = $('#belong_ques').val();
        var nickname = $('#nickname').val();
        var user_role = $('#user_role').val();
        //var user_type = $('#user_type').val();
        var ag_type = $('#ag_type').val();
        var ag_status = $('#ag_status').val();
        if ((isSelectedIds.length < 1 && isSelectAll==3) || countRecord <=0 ) {
            gritterAlert('{{ 'Prompt'|trans }}','{{ 'Please check the data'|trans }}', 'error');
            return ;
        }
        var flag = false;
        var param = {};
        if (username.length >= 1) {
            param['username'] = username;
            flag = true;
        }
        if (nickname.length >= 1) {
            param['nickname'] = nickname;
            flag = true;
        }
        if (belong_ques!='') {
            param['belong_ques'] = belong_ques;
            flag = true;
        }
        if (user_role!='') {
            param['user_role'] = user_role;
            flag = true;
        }
        /*if (user_type!='') {
            param['user_type'] = user_type;
            flag = true;
        }*/
        if (ag_type!='') {
            param['ag_role'] = ag_type;
            flag = true;
        }
        if (ag_status!='') {
            param['ag_status'] = ag_status;
            flag = true;
        }
        {% if isEnableGroup %}
        var user_group = $('#user_group').val();
        if (user_group!='') {
            param['user_group'] = user_group;
            flag = true;
        }
        {% endif %}
        if (!flag) {
            gritterAlert('{{ 'Prompt'|trans }}', '{{ 'Please select at least one parameter value'|trans }}','error');
            return ;
        } else {
            if (ag_type == -1) {
                //如果修改成非坐席；判断是否有登录的；
                for (var i = 0;i < isSelectedIds.length;i++) {
                    var islogin = $('#grid-table').jqGrid('getRowData', isSelectedIds[i]).is_login;
                    if (islogin == 1) {
                        gritterAlert('{{ 'Prompt'|trans }}', '{{ 'There are seats in the selected logon, cannot be modified for non seat'|trans }}','error');
                        return ;
                    }
                }
            }
            var search =$('#grid-table').jqGrid('getGridParam'); //获取搜素条件
            var postData = '';
            if (isSelectAll==1) {
                //区分按钮；//获取grid 的搜索条件；
                postData = typeof(search.postData.fliter) != 'undefined' ? search.postData.fliter : '';
            }
            var isAll = isSelectAll == 1 ? 1 : 0;
            param['ids'] = isSelectedIds;
            param['isall'] = isAll;
            param['filter'] = postData;
            param['iscancel'] = isCancelSelect;
            var str = jsonToString(param);
            $.ajax({
                type: 'post',
                url: '{{ path('icsoc_agent_batch_update') }}',
                data: {'conditions':str},
                success: function (response) {
                    if (response.error) {
                        gritterAlert('{{ 'Prompt'|trans }}', response.message, 'error');
                    } else {
                        gritterAlert('{{ 'Prompt'|trans }}', response.message, 'success');
                        $('#theForm')[0].reset();
                        $('#grid-table').trigger("reloadGrid");
                        isSelectedIds =[];
                        $('#batch').attr('class', 'hide');
                    }
                }
            })
        }
    }

    //override dialog's title function to allow for HTML titles
    $.widget("ui.dialog", $.extend({}, $.ui.dialog.prototype, {
        _title: function(title) {
            var $title = this.options.title || '&nbsp;';
            if( ("title_html" in this.options) && this.options.title_html == true )
                title.html($title);
            else title.text($title);
        }
    }));
    /**
     * @param ag_num
     */
    function fn_login(ag_num)
    {
        $('#loginPhone2').val('');
        $('#home4').addClass('active');
        $('#check').addClass('active');
        $('#profile4').removeClass('active');
        $('#nocheck').removeClass('active');
        $('.loginAgNum').val(ag_num);
        $('#but1').attr('onclick','set_login(1)').html('登录');
        $('#but2').attr('onclick','set_login(2)').html('登录');
        $( "#dialog-confirm" ).removeClass('hide').dialog({
            resizable: false,
            modal: false,
            title_html: true,
            height:300,
            width:380,
            title: "<div class='widget-header'><h4 class='smaller'>{{ 'Login'|trans }}</h4></div>"
        }).dialog('open');
    }

    /**
     * 签入
     */
    function set_login(e)
    {
        var phone = '';
        var ag_num = '';
        switch(e){
            case 1:
                phone = $('#loginPhone').val();
                ag_num = $('.loginAgNum1').val();
                break;
            case 2:
                phone = $('#loginPhone2').val();
                ag_num = $('.loginAgNum2').val();
                if(phone.length < 7) {
                    gritterAlert('{{ 'Prompt'|trans }}', '分机号不能小于7位', 'error');
                    return;
                }
                break;
        }

        if(phone.substring(0,2) == '00' ){
            gritterAlert('{{ 'Prompt'|trans }}', "分机号不能以'00'开头", 'error');
            return;
        }
        $.ajax({
            url: "{{ path('icsoc_agent_login') }}",
            type:'POST',
            dataType:'json',
            data:{ag_num:ag_num,phone:phone},
            success: function (responce) {
                if(responce["error"] === 0)
                {
                    $('.loginAgNum').val('');
                    $( "#dialog-confirm").dialog("close");
                    setTimeout('gritterAlert("{{ 'Prompt'|trans }}", "{{ 'Checkin success'|trans }}", "success");$("#grid-table").trigger("reloadGrid");', 1000);
                }
                else
                {
                    gritterAlert('{{ 'Prompt'|trans }}', responce.message, 'error');
                }
            }
        });
    }

    /**
     * 签出
     * @param ag_num
     */
    function fn_logout(ag_num)
    {
        $.ajax({
            url: "{{ path('icsoc_agent_logout') }}",
            type:'POST',
            dataType:'json',
            data:{ag_num:ag_num},
            success: function(responce){
                if(responce["error"] === 0)
                {
                    $( "#dialog-confirm").dialog("close");
                    setTimeout('gritterAlert("{{ 'Prompt'|trans }}", "{{ 'Checkout success'|trans }}", "success"); $("#grid-table").trigger("reloadGrid")', 1000);
                }
                else
                {
                    gritterAlert('{{ 'Prompt'|trans }}', responce.message, 'error');
                }
            }
        });
    }

    /**
     * @param ag_num
     */
    function fn_edit(ag_num)
    {
        $('#loginPhone2').val('');
        $('#home4').addClass('active');
        $('#check').addClass('active');
        $('#profile4').removeClass('active');
        $('#nocheck').removeClass('active');
        $('.loginAgNum').val(ag_num);
        $('#but1').attr('onclick','set_edit(1)').html('修改');
        $('#but2').attr('onclick','set_edit(2)').html('修改');
        $( "#dialog-confirm" ).removeClass('hide').dialog({
            resizable: false,
            modal: false,
            title_html: true,
            height:300,
            width:380,
            title: "<div class='widget-header'><h4 class='smaller'>修改</h4></div>"
        }).dialog('open');
    }
    /**
     * 修改
     */
    function set_edit(e)
    {
        var phone = '';
        var ag_num = '';
        switch(e){
            case 1:
                phone = $('#loginPhone').val();
                ag_num = $('.loginAgNum1').val();
                break;
            case 2:
                phone = $('#loginPhone2').val();
                ag_num = $('.loginAgNum2').val();
                if(phone.length < 7) {
                    gritterAlert('{{ 'Prompt'|trans }}', '分机号不能小于7位', 'error');
                    return;
                }
                break;
        }

        if(phone.substring(0,2) == '00' ){
            gritterAlert('{{ 'Prompt'|trans }}', "分机号不能以'00'开头", 'error');
            return;
        }
        $.ajax({
            url: "{{ path('icsoc_agent_edit_phone') }}",
            type:'POST',
            dataType:'json',
            data:{ag_num:ag_num,phone:phone},
            success: function (responce) {
                if(responce["error"] === 0)
                {
                    $('.loginAgNum').val('');
                    $( "#dialog-confirm").dialog("close");
                    setTimeout('gritterAlert("{{ 'Prompt'|trans }}", "修改成功", "success");$("#grid-table").trigger("reloadGrid");', 1000);
                }
                else
                {
                    gritterAlert('{{ 'Prompt'|trans }}', responce.message, 'error');
                }
            }
        });
    }


    function selectAll(flag, v)
    {
        //如果是点击按钮来的就清空；
        if (v) {
            isCancelSelect = [];
            isSelectedIds = [];
            $('#selectNum').text(countRecord);
        }
        var grid = $('#grid-table');
        isSelectAll = flag;
        if (flag == 1) {
            grid.jqGrid('resetSelection');
            var ids = grid.getDataIDs();
            if (ids.length == 0 && countRecord == 0) {
                isCancelSelect = [];
                isSelectedIds = [];
                $('#selectNum').text(countRecord); //如果记录为空；置零；
                return ;
            }
            for (var i=0, il=ids.length; i < il; i++) {
                if (isCancelSelect.indexOf(ids[i]) == -1) {
                    grid.jqGrid('setSelection',ids[i], true);
                }
            }
        } else if (flag == 3) {
            //普通点击
            //普通点击全选
            if (countRecord == 0) {
                isCancelSelect = [];
                isSelectedIds = [];
                $('#selectNum').text(countRecord); //如果记录为空；置零
                return ;
            }
            for (var i=0, il=isSelectedIds.length; i < il; i++) {
                grid.jqGrid('setSelection',isSelectedIds[i], true);
            }
        } else {
            isCancelSelect = [];
            isSelectedIds = [];
            isSelectAll = 3;//重置成3
            $('#selectNum').text(0);
            grid.jqGrid('resetSelection');
        }
    }
    function exportAgent()
    {
        if ((isSelectedIds.length < 1 && isSelectAll==3) || countRecord <=0 ) {
            gritterAlert('{{ 'Prompt'|trans }}','{{ 'Please check the data'|trans }}', 'error');
            return ;
        }
        var search =$('#grid-table').jqGrid('getGridParam');
        var postData = '';
        if (isSelectAll==1) {
            //区分按钮；//获取grid 的搜索条件；
             postData = typeof(search.postData.fliter) != 'undefined' ? search.postData.fliter : '';
        }
        var isAll = isSelectAll == 1 ? 1 : 0;
        var sord = search.postData.sord;
        var sidx = search.postData.sidx;
        location.href="{{ path('icsoc_agent_export_agent') }}?filter="+postData+'&sord='+sord+'&sidx='+sidx+'&ids='+isSelectedIds+'&isall='+isAll+'&iscancelIds='+isCancelSelect;
    }

    //刷新所有静态坐席
    function resetAllReadyAgent()
    {
        $( "#dialog-resetAllReady" ).removeClass('hide').dialog({
            resizable: false,
            title_html: true,
            height:"auto",
            width:250,
            modal: true,
            title: "<div class='widget-header'><h4 class='smaller'>刷新</h4></div>",
            buttons: {
                "确认": function() {
                    $( this ).dialog( "close" );
                    $.ajax({
                        url:"{{ path('icsoc_agent_reset_all') }}",
                        type:"get",
                        dataType:'json',
                        success:function(responce){
                            if(responce.code == 200)
                            {
                                gritterAlert('{{ 'Prompt'|trans }}','成功','success');
                            } else {
                                gritterAlert('{{ 'Prompt'|trans }}','失败','error');
                            }
                        }
                    });
                },
                '取消': function() {
                    $( this ).dialog( "close" );
                }
            }
        }).dialog('open');
    }

    function processData(rowId, status)
    {
        if (!status && isCancelSelect.indexOf(rowId) == -1) {
            isCancelSelect.push(rowId);
        } else if (status && isCancelSelect.indexOf(rowId) != -1) {
            //如果又选中了就要从isCancelSelect中去掉
            var index = isCancelSelect.indexOf(rowId);
            isCancelSelect.remove(index);
        }
        if (status && isSelectAll == 3 && isSelectedIds.indexOf(rowId) == -1) {
            isSelectedIds.push(rowId);
        } else if (isSelectAll == 3 && !status) {
            var index = isSelectedIds.indexOf(rowId);
            isSelectedIds.remove(index);
        }
    }

    // 多选 select 数据初始化
    function chose_mult_set_ini(select, values) {
        var arr = values.split(',');
        var length = arr.length;
        var value = '';
        for (i = 0; i < length; i++) {
            value = arr[i];
            $(select + " option[value='" + value + "']").attr('selected', 'selected');
        }
        $(select).trigger('chosen:updated');
    }

    /**
     * 坐席登录状态操作
     */
    function agent_operate(ag_id,code)
    {
        $.ajax({
            url:"{{ path('icsoc_monitor_system_agent_opr') }}",
            data:{"ag_id":ag_id,code:code},
            type:"post",
            dataType:'json',
            success:function(responce){
                if(responce.err == 0)
                {
                    $('#grid-table').trigger('reloadGrid');
                    gritterAlert('{{ 'Prompt'|trans }}','{{ 'Force to sign out successfully!'|trans }}','success');
                } else {
                    gritterAlert('{{ 'Prompt'|trans }}',responce.msg,'error');
                }
            }
        });
    }

    $(document).ready(function () {
        $("#dialog-confirm").dialog({autoOpen: false});
        $('#keyword').tooltip();
        $('#loginPhone').chosen({allow_single_deselect:true});
        $('#loginPhone').next().addClass('col-xs-10 col-sm-5').css({'width':'55%','height':'34'});
        $('.chosen-results').css('max-height','120px');
/*        $(window).on('resize.chosen', function() {
            $('.chosen-select').next().addClass('col-xs-10 col-sm-5').css({'width':'90%','height':'34'});
            $('.chosen-drop').css({'width':'90%'});
            $('.chosen-results').css('max-height','120px');
        }).trigger('resize.chosen');*/
    });
    </script>
{% endblock %}